<template>
  <div class="area-send-message" v-loading="loading">
    <fromSmtpAddress style="margin-top:10px" v-if="scriptItem.emailFromId" v-model="dataForm[scriptItem.emailFromId]"></fromSmtpAddress>
    <div class="area-send-message-top">
      <div class="toText" v-show="!scriptItem.labelShow">{{scriptItem.label}}</div>
      <div >
         <el-tooltip :open-delay="1000"  effect="dark" popper-class="tootipCheckGpList" :disabled="Array.isArray(checkGpList)&&checkGpList.length===0||!checkGpList"  placement="left">
          <div  slot="content"  v-html="tootipHander(checkGpList)"></div>
            
          <el-checkbox-group v-model="checkGpList"
                          @change="checkBoxGrounpChange">
          <el-select v-model="checkList"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    popper-class="select_box set-select-tips"
                    @change="selectBoxChagne"
                    @visible-change="selectVisibleChange"
                    @remove-tag="emailUsersplit"
                    :placeholder="$t('placeholder.sr')">
            <el-option-group v-for="(group,index) in options"
                            :key="index"
                            :label="group.label">
              <div v-if="!onlyShowUserList||onlyShowUserList&&index===2">
                <template v-if="group.options.length === 0 || group.options[0].nodata">
                  <el-option value="noDatasetField_defaultSelectNoData">
                    <div class="no-dataset-field">{{$t('statement.nds')}}</div>
                  </el-option>
                </template>
                <el-option v-else
                          v-for="(item,index2) in group.options"
                          :key="index2"
                          :label="item[scriptItem.emailLable]"
                          :value="index === 2 ? item[scriptItem.userName] :item[scriptItem.emailValue]">
                  <el-checkbox @click.native="(e) => {e.preventDefault()}"
                              :label="index === 2 ? item[scriptItem.userName] :item[scriptItem.emailValue]">{{item[scriptItem.emailLable]}}</el-checkbox>
                </el-option>
              </div>
            </el-option-group>
          </el-select>
          </el-checkbox-group>
         </el-tooltip>
        

       
      </div>

      <div class="to_cc_bcc"
           v-if="scriptItem.seedMessageBcc.length>0">
        <span v-for="(item,index) in localScriptItem"
              :key="index">
          <span v-if="!dataForm[item.text][item.emailChose]"
                @click="addBccEmail(item.label,item.text)">{{item.label}}&nbsp;&nbsp;&nbsp;</span>
        </span>
      </div>
    </div>
    <div v-if="scriptItem.seedMessageBcc.length>0"
         class="send-message_item">
      <div v-for="(item,i) in scriptItem.seedMessageBcc"
           :key="i">
        <type-send-message-bcc v-if="item.type ==='send-message'&&dataForm[item.text][item.emailChose]"
                               :dataForm='dataForm'
                               :scriptItem='item'>
        </type-send-message-bcc>
      </div>
    </div>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import fromSmtpAddress from '@/components/fromSmtpAddress/fromSmtpAddress.vue'
export default {
  name: 'TypeSendMessageBcc',
  inject: {botInfo:{default:()=>{}}},
  components: {
    fromSmtpAddress
  },
  props: {
    dataForm: {
      type: Object,
      default: () => { }
    },
    scriptItem: {
      type: Object,
      default: () => { }
    },
    onlyShowUserList: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      localScriptItem: null,
      selectDataObj: {},
      interfaceNoDataCount: 0,
      checkList: [],
      checkGpList: [],
      options: [{
        label: 'From Dataset Field',
        options: this.scriptItem[this.scriptItem.toSelectListField]
      }, {
        label: 'From Drill Through',
        options: []
      }, {
        label: 'From User List',
        options: []
      }],
      value: '',
      loading: false
    }
  },
  created () {
    // this.initDatasetFieldList()
    this.initComponent()
    this.localScriptItem = this._.cloneDeep(this.scriptItem.seedMessageBcc)
    this.concantEmailsUserList()
    if (this.botInfo() && this.botInfo().triggerType === 'Stream') {
      this.getTemplateParamsList()
    }
    this.scriptItem = JSON.parse(JSON.stringify(this.scriptItem))
  },
  computed: {
    datasetFieldList () {
      return this.scriptItem[this.scriptItem.toSelectListField]
    }
  },
  watch: {
    // datasetFieldList: {
    //   handler (val) {
    //     if (val.length === 0) {
    //       this.scriptItem[this.scriptItem.toSelectListField].push({
    //         nodata: true
    //       })
    //       this.options[0].options = this.scriptItem[this.scriptItem.toSelectListField]
    //     } else {
    //       let index = this.scriptItem[this.scriptItem.toSelectListField].findIndex(e => e.nodata)
    //       index > -1 && val.length > 1 && this.scriptItem[this.scriptItem.toSelectListField].splice(index, 1)
    //     }
    //     this.initDefUser()
    //   },
    //   deep: true
    // }
  },
  methods: {
     tootipHander (arr) {
      if (Array.isArray(arr)) {
        var str = ''
        arr.forEach(i => {
          str += i + '&nbsp;&nbsp;&nbsp;&nbsp;' + '<br>'
        })
        return str
      } else {
        return arr
      }
    },
    getTemplateParamsList () {
      var _self = this
      _self.$interface.schedule.getTemplateFieldsListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return _self.$message.error(res.msg)
          }
          var name
          if (_self.botInfo().sysBotScriptList.length === 1) {
            name = _self.botInfo().sysBotScriptList[0].paramsValue.type
          } else {
            var block = _self.botInfo().flowSetting.find(item => item.id === 0)
            var sysbot = _self.botInfo().sysBotScriptList.find(item => item.scriptId === block.blockId)
            name = sysbot.paramsValue.type
          }
          var result = res.data.find(i => i.name === name)
          result.info.forEach(item => {
            if (item.type === 'user') {
              var obj = {
                [this.scriptItem.emailLable]: item.key,
                [this.scriptItem.emailValue]: item.key,
                type: item.type
              }
              _self.options[0].options.push(obj)
            }
          })
        }).catch(() => { })
    },
    initDatasetFieldList () {
      if (this.datasetFieldList.length === 0) {
        this.scriptItem[this.scriptItem.toSelectListField].push({
          nodata: true
        })
      }
    },
    initComponent () {
      if (this.dataForm[this.scriptItem.text] === undefined || this.dataForm[this.scriptItem.text] === null) {
        this.dataForm[this.scriptItem.text] = this.scriptItem.defaultValue || ''
      }
      if (this.scriptItem.seedMessageBcc.length > 0) {
        this.scriptItem.seedMessageBcc.map(e => {
          if (this.dataForm[e.text] === undefined || this.dataForm[e.text] === null) {
            this.dataForm[e.text] = e.defaultValue || ''
          }
        })
      }
      this.getToSelectListFieldList()
      if (this.scriptItem.interfaceUrl) {
        this.getEmailSelectDataList(this.scriptItem)
      }
      if (this.scriptItem.userTypeFieldsUrl) {
        this.getUserTypeFieldstDataList(this.scriptItem)
      }
    },
    concantEmailsUserList () {
      this.checkList = this.dataForm[this.scriptItem.text][this.scriptItem.emailFields].concat(this.dataForm[this.scriptItem.text][this.scriptItem.selectValue])
    },
    initDefEmails () {
      if (this.scriptItem.emailLable !== this.scriptItem.emailValue) {
        this.options[2].options.forEach(element => {
          if (this.dataForm[this.scriptItem.text][this.scriptItem.emailFields].includes(element.id)) this.checkGpList.push(element[this.scriptItem.selectValue])
        })
      } else this.checkGpList = this.checkList
    },
    initDefUser () {
      if (this.scriptItem.emailLable !== this.scriptItem.emailValue) {
        this.options[0].options.forEach(element => {
          if (this.dataForm[this.scriptItem.text][this.scriptItem.selectValue].includes(element.id)) this.checkGpList.push(element[this.scriptItem.selectValue])
        })
      } else this.checkGpList = this.checkList
    },
    selectVisibleChange (e) {
      if (!e) {
        this.emailUsersplit()
      }
    },
    emailUsersplit (e) {
      let _self = this
      let allEmails = []
      let userEntryEmails = []
      let emailsList = []
      let userTypeFields = []
      for (let i = 0; i < _self.options.length; i++) {
        _self.options[i].options.forEach(element => {
          if (i === 0 && _self.checkList.includes(element[_self.scriptItem.emailValue])) userTypeFields.push(element[_self.scriptItem.emailValue])
          if (i === 1 && _self.checkList.includes(element[_self.scriptItem.emailValue])) userTypeFields.push(element[_self.scriptItem.emailValue])
          if (i === 2 && _self.checkList.includes(element[_self.scriptItem.emailValue])) emailsList.push(element[_self.scriptItem.emailValue])
          allEmails.push(element[_self.scriptItem.emailValue])
        })
      }
      _self.checkList.forEach(el => {
        if (!allEmails.includes(el)) userEntryEmails.push(el)
      })
      _self.dataForm[_self.scriptItem.text][_self.scriptItem.emailFields] = emailsList.concat(userEntryEmails)
      _self.dataForm[_self.scriptItem.text][_self.scriptItem.selectValue] = userTypeFields
    },
    getEmailSelectDataList (item) {
      const url = item.interfaceUrl
      const isTeamsList = url !== '/web/um/sys/user/list/select'
      const params = {
        status: isTeamsList?true:1
      }
      this.loading = true
      this.$interface.clientReport.getBoardListForBotApi(url, params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.resetDataLists(item)
            return this.$message.error(res.msg)
          }
          if (res.data) {
            let datas = res.data
            datas.forEach(it => {
              if (!it.hasOwnProperty(item.emailFields)) {
                it[item.emailFields] = it[item.emailValue]
              }
            })
            this.selectDataObj[`${item.text}ListsOrigin`] = datas
            this.selectDataObj = Object.assign({}, this.selectDataObj)
            this.options[2].options = this.selectDataObj[`${this.scriptItem.text}ListsOrigin`]
            this.loading = false
            this.initDefEmails()
            this.$forceUpdate()
            if (res.data.length <= 0) {
              this.resetDataLists(item)
            }
          }
        }).catch(() => {
          this.resetDataLists(item)
        })
    },
    getUserTypeFieldstDataList (item) {

    },
    resetDataLists: debounce(function (item) {
      this.interfaceNoDataCount++
      if (this.interfaceNoDataCount > 5) {
        return false
      }
      this.getEmailSelectDataList(item)
    }, 2000),
    getKeyList (param) {
      if (Array.isArray(param)) {
        this.scriptItem[this.scriptItem.toSelectListField] = param
      }
      this.dataForm[this.scriptItem.text] = JSON.parse(JSON.stringify(this.scriptItem.defaultValue))
    },
    getToSelectListFieldList () {
      let id = this.$store.state.bot.id
      let type = this.$store.state.bot.type
      this.scriptItem[this.scriptItem.toSelectListField] = []
      if (!id) {
        return
      }
      const params = {}
      type === 'dataset' && (params['datasetId'] = id)
      type === 'widget' && (params['gadgetId'] = id)
      params.showColumn = true
      this.$interface.reports.getFieldsListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.scriptItem[this.scriptItem.toSelectListField] = []
            return false
          }
          res.data.forEach(item => {
            if (item.type === 'user') {
              this.scriptItem[this.scriptItem.toSelectListField].push({
                [this.scriptItem.emailLable]: item.name,
                [this.scriptItem.emailValue]: item.name,
                type: item.type
              })
            }
          })
          this.options[0].options = this.scriptItem[this.scriptItem.toSelectListField]
          if (res.querySelectedColumns.length > 0) {
            var temp = res.querySelectedColumns
            temp.forEach(item => {
              item.data = item.data.filter(its => {
                return its.businessType === 'user'
              })
              item.data.forEach(i => {
                i[this.scriptItem.emailValue] = `${item.datasetName}#${i.alias}`
                this.options[1].options.push(i)
              })
            })
          }
          this.initDefUser()
        }).catch(() => {
          this.scriptItem[this.scriptItem.toSelectListField] = []
        })
    },
    checkBoxGrounpChange (e) {
      this.dataForm[this.scriptItem.text][this.scriptItem.emailFields] = e
    },
    selectBoxChagne (e) {
      let index = e.findIndex(res => res === 'noDatasetField_defaultSelectNoData')
      if (index > -1) {
        e.splice(index)
      }
      this.checkGpList = []
      this.checkList = e

      if (this.scriptItem.emailLable === this.scriptItem.emailValue) {
        this.checkGpList = e
      } else {
        this.options[1].options.forEach(element => {
          if (e.includes(element.id)) this.checkGpList.push(element[this.scriptItem.emailValue])
        })
        this.options[2].options.forEach(element => {
          if (e.includes(element.id)) this.checkGpList.push(element[this.scriptItem.emailValue])
        })
        this.options[0].options.forEach(element => {
          if (e.includes(element.id)) this.checkGpList.push(element[this.scriptItem.emailLable])
        })
      }
    },
    addBccEmail (type, text) {
      this.localScriptItem.forEach((element, index) => {
        if (type === element.label) {
          // this.localScriptItem.splice(index, 1)
          this.$set(element, 'display', true)
          // this.dataForm[this.scriptItem.text][this.scriptItem.emailChose] = true
          this.$set(this.dataForm[text], this.scriptItem.emailChose, true)
          this.$set(this.scriptItem.seedMessageBcc[index], 'display', true)
        }
      })
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .el-select-group__title {
  // background-color: #f0f0f0;
  // margin: 5px 16px;
}
.area-send-message {
  padding-top: 10px;
  width: 100%;
  // margin: 10px 0;
  .area-send-message-top {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 10px 0;
    // padding-top: 5px;
    box-shadow: 0px 1px 0px 0px #f0f0f0;
    margin-bottom: 1px;
    > div:nth-child(2) {
      flex: 1;
      > div:nth-child(1) {
        width: 100%;
      }
      ::v-deep .el-input__inner {
        border: 0;
      }
      ::v-deep .el-tag {
        height: 30px;
        line-height: 28px;
        background-color: #f0f0f0;
        color: #404040;
        margin: -1px 0 5px 11px;
      }
    }
  }
  .select,
  .email {
    // width: 50%;
    padding-left: 10px;
    display: flex;
    justify-content: flex-start;
    .check-bot {
      margin-right: 10px;
    }
  }
  ::v-deep .el-icon-arrow-up:before {
    content: "";
  }
  .email {
    margin-left: 15px;
  }

  .select_box {
    flex: 1;
  }
  .toText {
    font-size: 14px;
    font-weight: 400;
    color: #404040;
    line-height: 20px;
    margin-top: 6px;
  }
  .to_cc_bcc {
    // width: ;
    span {
      cursor: pointer;
    }
  }
  .send-message_item {
    > div:nth-child(1) {
      // box-shadow: 0px -1px 0px 0px #F0F0F0, 0px 1px 0px 0px #F0F0F0;
    }
    // >div:nth-child(2){
    //   box-shadow: 0px -1px 0px 0px #F0F0F0;
    // }
  }
}
</style>
<style lang="scss">
.set-select-tips {
  width: 355px !important;
  min-width: 355px !important;
  .no-dataset-field {
    display: inline-block;
    width: 100%;
    background: #e6f7ff;
    border-radius: 4px;
    font-weight: 400;
    color: #138dc7;
    // line-height: 20px;
    font-size: 14px;
    padding: 0 10px;
    white-space: normal;
    cursor: default;
  }
}
</style>
